/**
 * 
 */
package com.emovimento.synchronize;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.WatchEvent;

/**
 * Synchronizes a watched directory with the given destination directory.
 */
public class SynchronizingDirectoryWatcher extends DirectoryWatcher {
  private Path destinationDirectory;

  public SynchronizingDirectoryWatcher(final Path sourceDirectory, final Path destinationDirectory) throws IOException {
    super(sourceDirectory);
    this.destinationDirectory = destinationDirectory;
  }

  @Override
  protected void entryCreated(WatchEvent<?> pathWatchEvent, final Path directory, final Path createdPath) throws IOException {
    copyWithoutNotifications(createdPath, destinationDirectory.resolve(createdPath.getFileName()));
  }

  @Override
  protected void entryDeleted(WatchEvent<?> pathWatchEvent, final Path directory, final Path deletedPath) throws IOException {
    Files.delete(destinationDirectory.resolve(deletedPath.getFileName()));
  }

  @Override
  protected void entryModified(WatchEvent<?> pathWatchEvent, final Path directory, final Path modifiedPath) throws IOException {
    copyWithoutNotifications(modifiedPath, destinationDirectory.resolve(modifiedPath.getFileName()));
  }

  private void copyWithoutNotifications(Path source, Path target) throws IOException {
    boolean wasRegistered = unregister(target);
    Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
    if (wasRegistered) register(target);
  }
}
